package com.dmai.capacity.platform.user.service.impl;

import com.dmai.capacity.platform.common.constant.CodeEnum;
import com.dmai.capacity.platform.common.constant.CommonConstant;
import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.PageResultData;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.oauth.common.util.AuthUtils;
import com.dmai.capacity.platform.user.mapper.SysLogDao;
import com.dmai.capacity.platform.user.model.SysLog;
import com.dmai.capacity.platform.user.pojo.request.LogCreateRequest;
import com.dmai.capacity.platform.user.service.ISysLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class SysLogServiceImpl implements ISysLogService {

    @Autowired
    private SysLogDao logDao;

    @Transactional
    @Override
    public int save(LogCreateRequest request) {
        int i = 0;
        LoginAppUser loginAppUser = AuthUtils.getLoginAppUser();
        SysLog log;
        for (String content : request.getContents()) {
            log = new SysLog();
            log.setModule(request.getModule());
            log.setBusinessKey(request.getBusinessKey());
            log.setContent(content);
            log.setFlag("1");
            log.setCreateTime(new Date());
            log.setCreateUserid(loginAppUser.getId());
            log.setCreateUsername(loginAppUser.getRealname());
            log.setTenantId(loginAppUser.getTenantId());
            i += logDao.save(log);
        }

        return i;
    }

    @Override
    public int saves(List<LogCreateRequest> logs) {
        int c = 0;
        for (LogCreateRequest i : logs) {
            c += save(i);
        }
        return c;
    }

    @Override
    public PageResult<SysLog> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, CommonConstant.PAGE_CURRENT) != null && MapUtils.getInteger(params, CommonConstant.PAGE_SIZE) != null)
            PageHelper.startPage(MapUtils.getInteger(params, CommonConstant.PAGE_CURRENT), MapUtils.getInteger(params, CommonConstant.PAGE_SIZE), true);

        List<SysLog> list = logDao.findAll(params);
        PageInfo<SysLog> pageInfo = new PageInfo(list);

        return PageResult.<SysLog>builder().data(PageResultData.<SysLog>builder().records(pageInfo.getList()).total(pageInfo.getTotal()).pages(pageInfo.getPages()).build()).code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();

    }

}
